package org.soc.timesheet.controller;

import java.io.UnsupportedEncodingException;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import org.joda.time.format.DateTimeFormat;
import org.soc.timesheet.domain.Projects;
import org.soc.timesheet.domain.SubProjects;
import org.soc.timesheet.server.domain.service.ProjectsService;
import org.soc.timesheet.server.domain.service.SubProjectsService;
import org.soc.timesheet.server.domain.service.TimesheetService;
import org.soc.timesheet.server.domain.service.UsersProjectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.roo.addon.web.mvc.controller.json.RooWebJson;
import org.springframework.roo.addon.web.mvc.controller.scaffold.RooWebScaffold;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.UriComponentsBuilder;
import org.springframework.web.util.UriUtils;
import org.springframework.web.util.WebUtils;

@RequestMapping("/subprojectses")
@Controller
@RooWebScaffold(path = "subprojectses", formBackingObject = SubProjects.class)
@RooWebJson(jsonObject = SubProjects.class)
public class SubProjectsController {

	@Autowired
	ProjectsService projectService;

	@RequestMapping(value = "/project/{id}", headers = "Accept=application/json", method = RequestMethod.GET)
	@ResponseBody
	public ResponseEntity<List<SubProjects>> getSubProjectsByIdProject(
			HttpServletRequest request, HttpServletResponse response,
			@PathVariable("id") int idProject) {
		HttpHeaders header = getHeders();
		Projects project = projectService.findProjects(idProject);
		List<SubProjects> subProjects = subProjectsService
				.findByProject(project);

		return new ResponseEntity<List<SubProjects>>(subProjects, header,
				HttpStatus.OK);

	}

	private HttpHeaders getHeders() {
		HttpHeaders header = new HttpHeaders();
		header.add("Content-Type", "application/json");
		return header;
	}

	@RequestMapping(value = "/project/{id}/{page}/{limit}", headers = "Accept=application/json", method = RequestMethod.GET)
	@ResponseBody
	public ResponseEntity<Page<SubProjects>> getSubProjectsByIdProject(
			@PathVariable("id") int idProject, @PathVariable("page") int page,
			@PathVariable("limit") int limit,
			@RequestHeader(value = "filters", required = false) String filters) {
		
		
		
		PageRequest pageRequest = new PageRequest(page, limit);
		
		Projects project = projectService.findProjects(idProject);
		Page<SubProjects> result = subProjectsService
				.findByProject(project,pageRequest);

		return new ResponseEntity<Page<SubProjects>>(result,getHeders(), HttpStatus.OK);
	}

	@RequestMapping(value = "/{id}", method = RequestMethod.GET, headers = "Accept=application/json")
    @ResponseBody
    public ResponseEntity<String> showJson(@PathVariable("id") Integer id) {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json; charset=utf-8");
        try {
            SubProjects subProjects = subProjectsService.findSubProjects(id);
            if (subProjects == null) {
                return new ResponseEntity<String>(headers, HttpStatus.NOT_FOUND);
            }
            return new ResponseEntity<String>(subProjects.toJson(), headers, HttpStatus.OK);
        } catch (Exception e) {
            return new ResponseEntity<String>("{\"ERROR\":"+e.getMessage()+"\"}", headers, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

	@RequestMapping(headers = "Accept=application/json")
    @ResponseBody
    public ResponseEntity<String> listJson() {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json; charset=utf-8");
        try {
            List<SubProjects> result = subProjectsService.findAllSubProjectses();
            return new ResponseEntity<String>(SubProjects.toJsonArray(result), headers, HttpStatus.OK);
        } catch (Exception e) {
            return new ResponseEntity<String>("{\"ERROR\":"+e.getMessage()+"\"}", headers, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

	@RequestMapping(method = RequestMethod.POST, headers = "Accept=application/json")
    public ResponseEntity<String> createFromJson(@RequestBody String json, UriComponentsBuilder uriBuilder) {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json");
        try {
            SubProjects subProjects = SubProjects.fromJsonToSubProjects(json);
            subProjectsService.saveSubProjects(subProjects);
            RequestMapping a = (RequestMapping) getClass().getAnnotation(RequestMapping.class);
            headers.add("Location",uriBuilder.path(a.value()[0]+"/"+subProjects.getId().toString()).build().toUriString());
            return new ResponseEntity<String>(headers, HttpStatus.CREATED);
        } catch (Exception e) {
            return new ResponseEntity<String>("{\"ERROR\":"+e.getMessage()+"\"}", headers, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

	@RequestMapping(value = "/jsonArray", method = RequestMethod.POST, headers = "Accept=application/json")
    public ResponseEntity<String> createFromJsonArray(@RequestBody String json) {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json");
        try {
            for (SubProjects subProjects: SubProjects.fromJsonArrayToSubProjectses(json)) {
                subProjectsService.saveSubProjects(subProjects);
            }
            return new ResponseEntity<String>(headers, HttpStatus.CREATED);
        } catch (Exception e) {
            return new ResponseEntity<String>("{\"ERROR\":"+e.getMessage()+"\"}", headers, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

	@RequestMapping(value = "/{id}", method = RequestMethod.PUT, headers = "Accept=application/json")
    public ResponseEntity<String> updateFromJson(@RequestBody String json, @PathVariable("id") Integer id) {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json");
        try {
            SubProjects subProjects = SubProjects.fromJsonToSubProjects(json);
            subProjects.setId(id);
            if (subProjectsService.updateSubProjects(subProjects) == null) {
                return new ResponseEntity<String>(headers, HttpStatus.NOT_FOUND);
            }
            return new ResponseEntity<String>(headers, HttpStatus.OK);
        } catch (Exception e) {
            return new ResponseEntity<String>("{\"ERROR\":"+e.getMessage()+"\"}", headers, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

	@RequestMapping(value = "/{id}", method = RequestMethod.DELETE, headers = "Accept=application/json")
    public ResponseEntity<String> deleteFromJson(@PathVariable("id") Integer id) {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json");
        try {
            SubProjects subProjects = subProjectsService.findSubProjects(id);
            if (subProjects == null) {
                return new ResponseEntity<String>(headers, HttpStatus.NOT_FOUND);
            }
            subProjectsService.deleteSubProjects(subProjects);
            return new ResponseEntity<String>(headers, HttpStatus.OK);
        } catch (Exception e) {
            return new ResponseEntity<String>("{\"ERROR\":"+e.getMessage()+"\"}", headers, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

	@Autowired
    SubProjectsService subProjectsService;

	@Autowired
    ProjectsService projectsService;

	@Autowired
    TimesheetService timesheetService;

	@Autowired
    UsersProjectService usersProjectService;

	@RequestMapping(method = RequestMethod.POST, produces = "text/html")
    public String create(@Valid SubProjects subProjects, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) {
        if (bindingResult.hasErrors()) {
            populateEditForm(uiModel, subProjects);
            return "subprojectses/create";
        }
        uiModel.asMap().clear();
        subProjectsService.saveSubProjects(subProjects);
        return "redirect:/subprojectses/" + encodeUrlPathSegment(subProjects.getId().toString(), httpServletRequest);
    }

	@RequestMapping(params = "form", produces = "text/html")
    public String createForm(Model uiModel) {
        populateEditForm(uiModel, new SubProjects());
        return "subprojectses/create";
    }

	@RequestMapping(value = "/{id}", produces = "text/html")
    public String show(@PathVariable("id") Integer id, Model uiModel) {
        addDateTimeFormatPatterns(uiModel);
        uiModel.addAttribute("subprojects", subProjectsService.findSubProjects(id));
        uiModel.addAttribute("itemId", id);
        return "subprojectses/show";
    }

	@RequestMapping(produces = "text/html")
    public String list(@RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size, @RequestParam(value = "sortFieldName", required = false) String sortFieldName, @RequestParam(value = "sortOrder", required = false) String sortOrder, Model uiModel) {
        if (page != null || size != null) {
            int sizeNo = size == null ? 10 : size.intValue();
            final int firstResult = page == null ? 0 : (page.intValue() - 1) * sizeNo;
            uiModel.addAttribute("subprojectses", SubProjects.findSubProjectsEntries(firstResult, sizeNo, sortFieldName, sortOrder));
            float nrOfPages = (float) subProjectsService.countAllSubProjectses() / sizeNo;
            uiModel.addAttribute("maxPages", (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1 : nrOfPages));
        } else {
            uiModel.addAttribute("subprojectses", SubProjects.findAllSubProjectses(sortFieldName, sortOrder));
        }
        addDateTimeFormatPatterns(uiModel);
        return "subprojectses/list";
    }

	@RequestMapping(method = RequestMethod.PUT, produces = "text/html")
    public String update(@Valid SubProjects subProjects, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) {
        if (bindingResult.hasErrors()) {
            populateEditForm(uiModel, subProjects);
            return "subprojectses/update";
        }
        uiModel.asMap().clear();
        subProjectsService.updateSubProjects(subProjects);
        return "redirect:/subprojectses/" + encodeUrlPathSegment(subProjects.getId().toString(), httpServletRequest);
    }

	@RequestMapping(value = "/{id}", params = "form", produces = "text/html")
    public String updateForm(@PathVariable("id") Integer id, Model uiModel) {
        populateEditForm(uiModel, subProjectsService.findSubProjects(id));
        return "subprojectses/update";
    }

	@RequestMapping(value = "/{id}", method = RequestMethod.DELETE, produces = "text/html")
    public String delete(@PathVariable("id") Integer id, @RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size, Model uiModel) {
        SubProjects subProjects = subProjectsService.findSubProjects(id);
        subProjectsService.deleteSubProjects(subProjects);
        uiModel.asMap().clear();
        uiModel.addAttribute("page", (page == null) ? "1" : page.toString());
        uiModel.addAttribute("size", (size == null) ? "10" : size.toString());
        return "redirect:/subprojectses";
    }

	void addDateTimeFormatPatterns(Model uiModel) {
        uiModel.addAttribute("subProjects_startdate_date_format", DateTimeFormat.patternForStyle("MM", LocaleContextHolder.getLocale()));
        uiModel.addAttribute("subProjects_enddate_date_format", DateTimeFormat.patternForStyle("MM", LocaleContextHolder.getLocale()));
    }

	void populateEditForm(Model uiModel, SubProjects subProjects) {
        uiModel.addAttribute("subProjects", subProjects);
        addDateTimeFormatPatterns(uiModel);
        uiModel.addAttribute("projectses", projectsService.findAllProjectses());
        uiModel.addAttribute("timesheets", timesheetService.findAllTimesheets());
        uiModel.addAttribute("usersprojects", usersProjectService.findAllUsersProjects());
    }

	String encodeUrlPathSegment(String pathSegment, HttpServletRequest httpServletRequest) {
        String enc = httpServletRequest.getCharacterEncoding();
        if (enc == null) {
            enc = WebUtils.DEFAULT_CHARACTER_ENCODING;
        }
        try {
            pathSegment = UriUtils.encodePathSegment(pathSegment, enc);
        } catch (UnsupportedEncodingException uee) {}
        return pathSegment;
    }
}
